using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Tequila.Phone.Interactivity
{
    /// <summary>
    /// Enter <see cref="Key">key</see> down <see cref="TriggerBase{T}">trigger</see> generic implementation.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EnterKeyDownUpdateSourceTrigger<T> : TriggerBase<T> where T : FrameworkElement
    {
        /// <summary>
        /// Called after the trigger is attached to an AssociatedObject.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.KeyDown += OnKeyDown;
        }

        /// <summary>
        /// Called when the trigger is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        protected override void OnDetaching()
        {
            AssociatedObject.KeyDown -= OnKeyDown;
        }

        /// <summary>
        /// Triggers custom actions when Enter <see cref="Key">key</see> down event occured.
        /// </summary>
        protected virtual void Trigger()
        {
            InvokeActions(null);
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Trigger();
            }
        }
    }
}